import 'dart:async';
import 'dart:convert';

import 'package:alipay_kit/alipay_kit.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:wechat_kit/wechat_kit.dart';

import '../../base/Constant.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../util/LoadingUtil.dart';
import '../../util/SignUtil.dart';

///
// * 订单支付页面
// * @author weimengmeng
// * @date 2019-08-30 17:08
// * 包括微信支付和支付宝支付
///
class OrderPayPage extends StatefulWidget {
  String orderId, orderNum, totalMoney, title,discount;

  OrderPayPage(
      {Key key,
      @required this.orderId,
      @required this.orderNum,
      @required this.totalMoney,
      this.discount,
      this.title})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return OrderPayView(orderId, orderNum, totalMoney);
  }
}

class OrderPayView extends State<OrderPayPage> {
  String orderId, orderNum, totalMoney, token;
  int groupValue = 1;
  Wechat _wechat = Wechat()
    ..registerApp(appId: WX_APPID, universalLink: "https://do.com/");
  StreamSubscription<WechatPayResp> _pay;
  OrderPayView(this.orderId, this.orderNum, this.totalMoney);
  bool isShow = true;

  static const bool _ALIPAY_USE_RSA2 = true;
  static const String _ALIPAY_APPID = 'your alipay appId'; // 支付/登录
  static const String _ALIPAY_PID = 'your alipay pid'; // 登录
  static const String _ALIPAY_TARGETID = 'your alipay targetId'; // 登录
  static const String _ALIPAY_PRIVATEKEY =
      'your alipay rsa private key(pkcs1/pkcs8)'; // 支付/登录
  Alipay _alipay = Alipay();
  StreamSubscription<AlipayResp> _apay;
  StreamSubscription<AlipayResp> _auth;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          "订单支付",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      body: new SingleChildScrollView(
        child: new Container(
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                color: divideColor,
                height: ScreenUtil.getInstance().setWidth(DP_20),
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20),
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20)),
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '订单编号',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                      flex: 2,
                    ),
                    Expanded(
                      child: Text(
                      '$orderNum',
                      maxLines: 2,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black38),
                    )
                    )
                    
                  ],
                ),
              ),
              Container(
                color: divideColor,
                height: 1,
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20),
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20)),
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '订单金额',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                      flex: 2,
                    ),
                    Text(
                      widget.discount==null?widget.totalMoney:formatNum(double.parse(widget.totalMoney)+double.parse(widget.discount), 2),
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black38),
                    )
                  ],
                ),
              ),
              Container(
                color: divideColor,
                height: 1,
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20),
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20)),
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '优惠金额',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                      flex: 2,
                    ),
                    Text(
                      widget.discount==null||widget.discount=='null'?'0':formatNum(double.parse(widget.discount), 2),
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black38),
                    )
                  ],
                ),
              ),
              Container(
                color: divideColor,
                height: 1,
              ),
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20),
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20)),
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        '实际支付',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                      flex: 2,
                    ),
                    Text(MONEY + formatNum(double.parse(totalMoney),2),
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: mainColor))
                  ],
                ),
              ),
              Container(
                color: divideColor,
                height: 1,
              ),
              Container(
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_30),
                    ScreenUtil.getInstance().setWidth(DP_20),
                    ScreenUtil.getInstance().setWidth(DP_10),
                    ScreenUtil.getInstance().setWidth(DP_30)),
                child: Text(
                  '选择支付方式 ',
                  style: TextStyle(
                      color: Colors.black,
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                ),
              ),
              new Container(
                alignment: Alignment.centerRight,
                child: new Column(
                  children: <Widget>[
                    // new Container(
                    //   color: Colors.white,
                    //   child: new Row(
                    //     children: <Widget>[
                    //       Expanded(
                    //         flex: 1,
                    //         child: Image.asset(
                    //           'images/privilege_b_selected.png',
                    //           width: ScreenUtil.getInstance().setWidth(DP_60),
                    //           height: ScreenUtil.getInstance().setWidth(DP_60),
                    //         ),
                    //       ),
                    //       Expanded(
                    //         flex: 4,
                    //         child: Text('余额支付',
                    //             style: TextStyle(
                    //                 color: Colors.black,
                    //                 fontSize: ScreenUtil.getInstance()
                    //                     .setSp(NORMAL_FONT_SIZE))),
                    //       ),
                    //       CircularCheckBox(
                    //           value: groupValue == 0,
                    //           activeColor: mainColor,
                    //           // groupValue: groupValue,
                    //           onChanged: (T) {
                    //             setState(() {
                    //               groupValue = 0;
                    //             });
                    //           }),
                    //     ],
                    //   ),
                    // ),
                    Container(
                      color: divideColor,
                      height: 1,
                    ),
                    new Container(
                      color: Colors.white,
                      child: new Row(
                        children: <Widget>[
                          Expanded(
                            flex: 1,
                            child: Image.asset(
                              'images/icon_ipay.png',
                              width: ScreenUtil.getInstance().setWidth(DP_60),
                              height: ScreenUtil.getInstance().setWidth(DP_60),
                            ),
                          ),
                          Expanded(
                            flex: 4,
                            child: Text('支付宝支付',
                                style: TextStyle(
                                    color: Colors.black,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE))),
                          ),
                          Checkbox(
                              value: groupValue == 1,
                              activeColor: mainColor,
                              // groupValue: groupValue,
                              onChanged: (T) {
                                setState(() {
                                  groupValue = 1;
                                });
                              }),
                        ],
                      ),
                    ),
                    Container(
                      color: divideColor,
                      height: 1,
                    ),
                    Offstage(
                      offstage: isShow,
                      child: new Container(
                        color: Colors.white,
                        child: new Row(
                          children: <Widget>[
                            Expanded(
                              flex: 1,
                              child: Image.asset(
                                'images/icon_wechat.png',
                                width: ScreenUtil.getInstance().setWidth(DP_60),
                                height:
                                    ScreenUtil.getInstance().setWidth(DP_60),
                              ),
                            ),
                            Expanded(
                              flex: 4,
                              child: Text('微信支付',
                                  style: TextStyle(
                                      color: Colors.black,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE))),
                            ),
                            Checkbox(
                                value: groupValue == 2,
                                activeColor: mainColor,
                                onChanged: (T) {
                                  setState(() {
                                    groupValue = 2;
                                  });
                                }),
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              ),
              GestureDetector(
                onTap: ()async{
                    showDialog(
                        context: context,
                        barrierDismissible: false,
                        builder: (_) {
                          return new NetLoadingDialog(
                            loadingText: "支付中...",
                            bgColor: Color.fromARGB(255, 0, 0, 0),
                            requestCallBack: null,
                            outsideDismiss: false,
                          );
                        });
                    getOrderForm();
                    // var result = await FlutterAlipay.pay("you pay info from server");
                    // print(result);
                },
                child: new Container(
                width: double.infinity,
                alignment: Alignment.center,
                height: ScreenUtil.getInstance().setWidth(DP_80),
                margin: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setWidth(DP_100),
                    ScreenUtil.getInstance().setWidth(DP_80),
                    ScreenUtil.getInstance().setWidth(DP_100),
                    0),
                decoration: new BoxDecoration(
                    color: mainColor,
                    borderRadius: BorderRadius.circular(
                        ScreenUtil.getInstance().setWidth(DP_80))),
                // child: new FlatButton(
                  child: new Padding(
                    padding: EdgeInsets.all(0.0),
                    child: new Text(
                      "立即支付",
                      style: new TextStyle(
                          color: Colors.white,
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                    ),
                  // ),
                  
                ),
              )
              )
              
            ],
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
    });
    _pay = _wechat.payResp().listen(_listenPay);
    checkWx();
    _apay = _alipay.payResp().listen(_listenaPay);
    _auth = _alipay.authResp().listen(_listenAuth);
  }

  void _listenaPay(AlipayResp resp) {
    String content = 'pay: ${resp.resultStatus} - ${resp.result}';

    switch ('${resp.resultStatus}') {
      case "9000":
        Fluttertoast.showToast(msg: "订单支付成功");
        Navigator.popAndPushNamed(context, '/');
        break;
      case "8000":
        Fluttertoast.showToast(msg: "正在处理中");
        break;
      case "4000":
        Fluttertoast.showToast(msg: "订单支付失败");
        break;
      case "6001":
        Fluttertoast.showToast(msg: "取消支付");
        break;
      case "6002":
        Fluttertoast.showToast(msg: "网络连接出错");
        break;
      default:
    }
    // _showTips('支付', content);
  }

  void _listenAuth(AlipayResp resp) {
    String content = 'pay: ${resp.resultStatus} - ${resp.result}';
    _showTips('授权登录', content);
  }

  void _showTips(String title, String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(title),
          content: Text(content),
        );
      },
    );
  }

  checkWx() async {
    if (await _wechat.isInstalled()) {
      setState(() {
        isShow = false;
      });
    } else {
      setState(() {
        isShow = true;
      });
    }
  }
String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }
  getOrderForm() async {
    Map map = new Map();
    map['token'] = token;
    map['order_id'] = widget.orderId.toString();
    map['pay_method'] =
        groupValue == 0 ? "balance" : groupValue == 1 ? "alipay" : "wxpay";
    map['sign_type'] = createSignType(Api.URL_ORDER_PAYFORM);

    // if( map['pay_method'] =='wxpay'){
    //   Navigator.of(context).pop(1);
    //   Fluttertoast.showToast(msg: '工程师正在开发中...');
    //   return;
    // }
    // print(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_ORDER_PAYFORM, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    // print(userMap);
    if (code == 1) {
       if (groupValue == 0) {

       }
      else if (groupValue == 1) {
        _alipay.payOrderSign(orderInfo: userMap['data']['pay_parameters']);
      } else {
        print(userMap['data']['pay_parameters']);
        String str = json.encode(userMap['data']['pay_parameters']);
        Map map =
            json.decode(str.substring(1, str.length - 1).replaceAll("\\", ""));
        print(map['appid']);
        _wechat.pay(
          appId: WX_APPID,
          partnerId: map['partnerid'],
          prepayId: map['prepayid'],
          package: map['package'],
          nonceStr: map['noncestr'],
          timeStamp: map['timestamp'].toString(),
          sign: map['sign'],
        );
      }
    } else {
      Fluttertoast.showToast(msg: msg);
    }
  }

  void _listenPay(WechatPayResp resp) {
    String content = 'pay: ${resp.errorCode} ${resp.errorMsg}';
    print(content);
    switch (resp.errorCode.toString()) {
      case "0":
        Fluttertoast.showToast(msg: "支付成功");
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new OrderPage(
        //     index: 2,
        //   );
        // }));
        break;
      case "-1":
        Fluttertoast.showToast(msg: "支付异常");
        break;
      case "-2":
        Fluttertoast.showToast(msg: "取消支付");
        break;
    }
  }

  @override
  void dispose() {
    if (_pay != null) {
      _pay.cancel();
    }
    super.dispose();
  }
}
